<template>
<div class="messagelayout">
  <!-- 列表栏 -->
            <div class="messagelist">
                <div class="messageheader">
                    <span>消息列表</span>
                </div> 

                <div class="messagelists">
                    <ul class="messagelistsul">   
                        <li class="messagelistli" v-for="i of messageList" :key="i.lasttime">                    
                                <div class="messageavaname" @click="getMessage(i.shield,i&&i.user&&i.user.id)">
                                    <div class="messageavatar">
                                        <el-avatar :src="i&&i.user&&i.user.imgurl"></el-avatar>
                                      
                                       <div v-if="i.tip!=0">
                                         <el-badge :value="i.tip" :max="99" class="item"></el-badge>  
                                       </div>

                                        <div class="messagename">
                                            <span>{{i&&i.user&&i.user.name}}</span>
                                        </div> 
                                    </div>  
                                    <div class="messagetime">  
                                            <span>{{dateformate(i.lasttime)}}</span>
                                    </div>  
                                </div>                 
                        </li>
                    </ul>
                </div>
            </div>

     <div class="messagecontent">
        <div class="messagedetaillayout">
            <div class="messagedetail">

                <div class="messageshow">
                    <ul>
                        <li v-for="i of messageDetailList" :key="i.time">
                            <div v-if="i.user_id!=userid" class="messagedetailli1">
                                <div id="avatar">
                                    <el-avatar :src="i&&i.user&&i.user.imgurl"></el-avatar> 
                                </div>
                                <div>
                                    <div id="name">
                                        <span>{{i&&i.user&&i.user.name}}</span>
                                    </div>
                                    <div id="message" v-if="i.types==0">
                                        <p>{{i.message}}</p> 
                                    </div>  
                                    <div id="message" v-if="i.types==1" >
                                        <img :src="i.message" alt="">
                                    </div>    
                                    <div id="message" v-if="i.types==2" class="fileshow">
                                        <el-button type="warning" icon="el-icon-folder-opened"></el-button>
                                        <div class="fileshowname">
                                            <p>{{filterFileName(i.message)}}</p>
                                            <div class="flexend">
                                                <div> </div>
                                                <a :href="i.message" download>点击下载</a>
                                            </div>     
                                        </div>  
                                    </div>      
                                </div>
                                 
                            </div>

                            <div v-if="i.user_id==userid" class="messagedetailli2">
                                <div>
                                    <div id="name">
                                        <div> </div>
                                        <span>{{i&&i.user&&i.user.name}}</span>
                                    </div>
                                    <div id="message" v-if="i.types==0">
                                        <p>{{i.message}}</p> 
                                    </div> 
                                    <div id="message" v-if="i.types==1">
                                        <img :src="i.message" alt="">
                                    </div>    
                                    <div id="message" v-if="i.types==2" class="fileshow">
                                        <el-button type="warning" icon="el-icon-folder-opened"></el-button>
                                        <div class="fileshowname">
                                            <p>{{filterFileName(i.message)}}</p>
                                            <div class="flexend">
                                                <div> </div>
                                                <a :href="i.message" download>点击下载</a>
                                            </div>     
                                        </div>  
                                    </div>   
                                </div>
                                <div id="avatar">
                                    <el-avatar :src="i&&i.user&&i.user.imgurl"></el-avatar> 
                                </div>    
                            </div> 
                        </li>
                    </ul>
                </div>

                        

                <div class="messageinput">
                    <div class="messageinputform">
                       <el-input
                            type="textarea"
                            :rows="2"
                            v-model="inputMessage">
                        </el-input> 
                    </div>

                      

                    <div class="messageinputbutton">
                        <el-popover
                            placement="top"
                            width="380"
                            trigger="hover">
                            <div class="container">
                                <!-- 
                                search: 'Search Results',
                                recent: 'Frequently Used',
                                people: 'Smileys & People',
                                nature: 'Animals & Nature',
                                foods: 'Food & Drink',
                                activity: 'Activity',
                                places: 'Travel & Places',
                                objects: 'Objects',
                                symbols: 'Symbols',
                                flags: 'Flags',
                                custom: 'Custom',-->
                                <picker
                                :include="['search','people','recent','foods','nature','activity','places','objects','symbols','flags','custom']"  
                                :showSearch="false"    
                                :showPreview="false" 
                                :showCategories="false"
                                @select="addEmoji"
                                />
                            </div>
                            <el-button slot="reference"  icon="el-icon-star-off" circle></el-button>
                        </el-popover>

                        <el-button icon="el-icon-folder-opened" circle  @click="fileDialogVisible = true"></el-button>
                        <el-button type="success" @click="sendMessage">发送</el-button>
                    </div>
                </div>
            </div> 
        </div>
     </div>
                    <div v-if="theType=='friend'">
                        <el-dialog
                            title="好友文件传输"
                            :visible.sync="fileDialogVisible"
                            width="30%"
                            >
                            <div>
                            <el-avatar :src="friendDetail.imgurl"></el-avatar> 
                            <div class="avatarandname">   
                                    <span>{{friendDetail.name}}</span>
                                    <span>{{dateformate(friendDetail.time)}}</span>
                            </div>
                            <div class="filemessage">
                                <form> 
                                    <span><i class="el-icon-picture-outline"></i> 图片传输</span>
                                    <input name="file" type="file" @change="sendImage"/>
                                     
                                </form>
                            </div>
                            
                            <div class="filemessage">  
                                <form>  
                                    <span><i class="el-icon-folder"></i> 文件传输</span>
                                    <input name="file" type="file" @change="sendFile" />
                                    
                                </form>
                            </div>
                            </div>
                            
                            <span slot="footer" class="dialog-footer">
                                <el-button type="primary" @click="fileDialogVisible = false">完 成</el-button>
                            </span>
                         </el-dialog> 
                    </div>

                    <div v-if="theType=='group'">
                        <el-dialog
                            title="群文件传输"
                            :visible.sync="fileDialogVisible"
                            width="30%"
                            >
                            <div>
                            <el-avatar :src="groupDetail.imgurl"></el-avatar> 
                            <div class="avatarandname">   
                                    <span>{{groupDetail.name}}</span>
                                    <span>{{dateformate(groupDetail.time)}}</span>
                            </div>
                            <div class="filemessage">  
                                <form>  
                                    <span><i class="el-icon-picture-outline"></i> 图片传输</span>
                                    <input name="file" type="file" @change="sendImage"/>
                                </form>
                            </div>
                            <div class="filemessage">  
                                <form>  
                                    <span><i class="el-icon-folder"></i> 文件传输</span>
                                    <input name="file" type="file" @change="sendFile" />
                                </form>
                            </div>
                            </div>
                            
                            <span slot="footer" class="dialog-footer">
                                <el-button type="primary" @click="fileDialogVisible = false">完 成</el-button>
                            </span>
                         </el-dialog> 
                    </div>
                        
</div>
 
  
</template>

<script>
import request from "../utils/request";
import { Picker } from "emoji-mart-vue";
export default{
    components: {Picker},

    data(){
        return{
            messageList:[],    //消息列表
            inputMessage:"",  //输入发送信息
            messageDetailList:[], //聊天消息详情
            fileDialogVisible: false,  //控制文件传输界面
            userid:"",//从cookie中获取的用户ID
            friendid:"",//好友ID
            groupid:"",//群ID
            theType:"",
            //用户信息
            detailData:{
                id:"",
                name:"",
                sex:"",
                birth:"",
                explain:"",
                imgurl:"",
                email:"",
                time:""
            },

            //当前好友信息
            friendDetail:{
                id:"",
                name:"",
                sex:"",
                birth:"",
                explain:"",
                imgurl:"",
                email:"",
                time:""
            },

            //当前群聊信息
            groupDetail:{
                id:"",
                user_id:"",
                name:"",
                imgurl:"",
                time:""
            },
            
            //文件列表
             fileList: []
        }
    },

    created(){
        this.getMessageList(); //获取消息列表
        this.getMyCookie();//获取用户ID
        this.getUserDetail();//获取用户信息

        if(this.userid){
            this.$socket.emit("login",{userid:this.userid});//与服务器建立连接

            this.sockets.subscribe('groupRes',data=>{//监听群聊信息
                    console.log(data)
                    if(this.groupid==data.group_id){
                        this.getGroupMessageList2(this.groupid);
                    }else{
                        this.getMessageList2();
                    }
                }); 

            this.sockets.subscribe('friendRes',data=>{//监听私聊信息
                    console.log("好友回复：",data)
                    if(this.friendid==data.user_id||this.userid==data.user_id){
                        console.log(this.friendid)
                        this.getFriendMessageList2(this.friendid);
                    }
                    this.getMessageList2();
                });
        }  
    },



    methods:{
        //提取文件名
        filterFileName(fileName){
            let start=fileName.lastIndexOf('/')+1
            return fileName.slice(start)
        },

        //表情包
        addEmoji(e) {
            this.inputMessage += e.native;
        },

        //文本消息传输
        sendMessage(){
            if(this.inputMessage){
                //发送好友消息
                if(this.theType=="friend"){

                   let sendFriendMessage={
                        //发送方信息
                        user_id:this.userid,
                        user:{
                            name:this.detailData.name,
                            imgurl:this.detailData.imgurl
                        },
                        //接收方信息
                        friend_id:this.friendid,
                        //消息内容
                        message:this.inputMessage,  
                        }

                //发送信息
                this.$socket.emit('sendFriendMessage',sendFriendMessage);
                this.inputMessage="";
                // 更新聊天记录
                this.getFriendMessageList2(this.friendid)
                this.sendFriendMessage={};
                //接收服务器消息推送
                this.sockets.subscribe('friendRes',data=>{
                    console.log(data)
                    if(this.friendid==data.user_id){             //如果当前界面是该好友，则直接显示聊天记录
                        this.getFriendMessageList2(data.user_id); 
                    }else{                                         //若不是，则更新消息列表
                        this.getMessageList2();
                    }
                }) 
              }else if(this.theType=="group"){//发送群消息
              let sendGroupMessage={
                   //发送方信息
                    user_id:this.userid,
                    user:{
                        name:this.detailData.name,
                        imgurl:this.detailData.imgurl
                    },
                    //群id
                    group_id:this.groupDetail.id,
                    //消息内容
                    message:this.inputMessage,  
                };
                //发送群消息
                this.$socket.emit('sendGroupMessage',sendGroupMessage);
                this.inputMessage="";
                // 更新聊天记录
                this.getGroupMessageList(this.groupid)
                this.sendGroupMessage={};
                //接收群消息
                this.sockets.subscribe('groupRes',data=>{
                    console.log(data)
                    if(this.groupid==data.group_id){
                        this.getGroupMessageList2(this.groupid);
                    }else{
                        this.getMessageList2();
                    }
                }) 
              }
                
            }    
        },

        //图片传输
        sendImage(e){
            e.preventDefault();
            //获取图片
            const files = e.target.files
            const rawFile = files[0]
            let formData = new FormData()
            formData.append("file", rawFile)

            if(this.theType=="friend"){
                document.cookie="friendid="+this.friendid;
                document.cookie="name="+this.detailData.name;
                document.cookie="imgurl="+this.detailData.imgurl;

                request.post('/sendFriendImage',formData);
                e.target.files="";
                this.getFriendMessageList2(this.friendid);
              
            }else if(this.theType=="group"){//发送群图片
                document.cookie="groupid="+this.groupDetail.id;
                document.cookie="name="+this.detailData.name;
                document.cookie="imgurl="+this.detailData.imgurl;

                request.post('/sendGroupImage',formData);
                e.target.files="";
                 // 更新聊天记录
                this.getGroupMessageList2(this.groupid)
            }
        },

        //文件传输
        sendFile(e){
            e.preventDefault();
            //获取图片
            const files = e.target.files
            const rawFile = files[0]
            let formData = new FormData()
            formData.append("file", rawFile)

            if(this.theType=="friend"){
                document.cookie="friendid="+this.friendid;
                document.cookie="name="+this.detailData.name;
                document.cookie="imgurl="+this.detailData.imgurl;

                request.post('/sendFriendFile',formData)
                 e.target.files=""; 
                //更新聊天记录
                this.getFriendMessageList2(this.friendid);

            }else if(this.theType=="group"){//发送群文件
                document.cookie="groupid="+this.groupDetail.id;
                document.cookie="name="+this.detailData.name;
                document.cookie="imgurl="+this.detailData.imgurl;

                request.post('/sendGroupFile',formData)
                 e.target.files="";
                 // 更新聊天记录
                this.getGroupMessageList2(this.groupid)
            }
        },

   
        //获取消息列表
        getMessageList(){
            request.get('/messageList').then((res)=>{
                this.messageList=res.data;
                console.log(res.data)
                this.getMessage(res.data[0].shield,res.data[0].user.id)
            })
        },
        
        //获取消息列表2（不返回首项的聊天记录）
        getMessageList2(){
            request.get('/messageList').then((res)=>{
                this.messageList=res.data;
            })
        },
       
       //获取聊天信息
       getMessage(shield,id){
           if(shield!=null){
               this.getGroupMessageList(id);
           }else{
              this.getFriendMessageList(id); 
           }
           
       },

       //获取指定好友聊天记录
       getFriendMessageList(id){ 
           this.theType="friend";  
           this.groupid="";
           this.friendid=id;
           request.get(`/getFriendMessageList/${id}`).then((res)=>{
               this.messageDetailList=res.data;
               console.log(res.data);
               this.getMessageList2();   
        });
          //获取该好友信息
            request.get(`/user/detail/${id}`).then((res)=>{
                this.friendDetail.id=res.data.id;
                this.friendDetail.name=res.data.name;
                this.friendDetail.sex=res.data.sex;
                this.friendDetail.birth=res.data.birth;
                this.friendDetail.explain=res.data.explain;
                this.friendDetail.imgurl=res.data.imgurl;
                this.friendDetail.email=res.data.email;
                this.friendDetail.time=new Date();
                });
       },

       //获取指定好友聊天记录
       getFriendMessageList2(id){ 
           this.theType="friend";  
           this.groupid="";
           this.friendid=id;
           request.get(`/getFriendMessageList2/${id}`).then((res)=>{
               this.messageDetailList=res.data;
               console.log(res.data);
               this.getMessageList2();   
        });
       },

       //获取指定群聊聊天记录
       getGroupMessageList(id){ 
           this.theType="group";
           this.friendid="";
           this.groupid=id;
           request.get(`/getGroupMessageList/${id}`).then((res)=>{
               this.messageDetailList=res.data;
               console.log(res.data);
               this.getMessageList2();
           });
           //获取当前群聊信息
           request.get(`/group/groupDetail/${id}`).then((res)=>{
            console.log(res.data);
            this.groupDetail.name=res.data.detailData.name;
            this.groupDetail.id=res.data.detailData.id;
            this.groupDetail.imgurl=res.data.detailData.imgurl;
            this.groupDetail.time=new Date()})
       },

       //获取指定群聊聊天记录
       getGroupMessageList2(id){ 
           this.theType="group";
           this.friendid="";
           this.groupid=id;
           request.get(`/getGroupMessageList2/${id}`).then((res)=>{
               this.messageDetailList=res.data;
               console.log(res.data);
               this.getMessageList2();
           });
       },
        
        
        //加载时获取用户信息
        getUserDetail(){
            request.get('/user/detail').then((res)=>{
                this.detailData.id=res.data.id;
                this.detailData.name=res.data.name;
                this.detailData.sex=res.data.sex;
                this.detailData.birth=res.data.birth;
                this.detailData.explain=res.data.explain;
                this.detailData.imgurl=res.data.imgurl;
                this.detailData.email=res.data.email;
                this.detailData.time=res.data.time;
            });
        },

          getMyCookie(){
              let cookieString=this.getCookie("userid");
              this.userid=parseInt(cookieString);
          },

          //获取指定cookie
          getCookie(cname){        
            var name = cname + "=";        
            var ca = document.cookie.split(';');        
            for(var i=0; i<ca.length; i++){        
                var c = ca[i].trim();        
                if(c.indexOf(name)==0) return c.substring(name.length,c.length);        
            }        
            return "";        
        },  

        //转换详情信息时间格式
        dateformatedetail(time) {
            let date = new Date(time);
            let year = date.getFullYear();
            let month = date.getMonth()+1;
            let day = date.getDate();
            let result = `${year}-${month}-${day}`;
            return result
        },
        //修改时间格式
        dateformate(time) {
            let date = new Date(time);
            let year = date.getFullYear();
            let month = date.getMonth()+1;
            let day = date.getDate();
            let hour = date.getHours();
            let minutes = date.getMinutes();
            let result = `${year}-${month}-${day} ${hour}:${minutes}`;
            return result
        },
        
    }
}
</script>

<style scoped>

* {
    box-sizing:border-box
}
.messagelayout{
width:100%;
height:100%;
background-color:#2c3e50; 
border-radius: 0px 40px 40px 0px;
display: flex;
justify-content:space-between;
}

.messagelist{
    height:100%;
    width:40%;
    padding:20px;
    padding-right: 15px;
    background-color: #2c3e50;
}
.messageheader{
    color: rgb(237, 241, 244);
    font-size: 18px;
    display: grid;
   place-items: center;
    background-color: #70b2f5;
    padding-bottom: 0px;
    padding-top:5px;
    height:10%;
    border-radius: 5px 5px 0px 0px;
}
 .messagelists{
     background-color: white;
     height:90%;
     overflow:auto;
     border-radius: 0px 0px 5px 5px;
     width:100%;
 }

 /* 设置滚动条的样式 */
::-webkit-scrollbar {
width:1px;
}

/* 列表样式 */
.messagelistli{
height:60px;
width:100%;
display: flex;
justify-content:space-between;
border-bottom:1px solid rgb(239, 241, 242)
}

.messagelistli:hover{
    background-color: rgb(203, 225, 244);
}

 .messageavaname{
    height:100%;
    display: flex;
    justify-content:space-between;
    width:100%;
}
.messageavatar{
   height:100%;
   display: flex;
   justify-content:flex-start;
   padding:10px
}
.messagename{
    height:100%;
    display: grid;
   place-items: center;
   color:#4c6986;
   padding:10px;
}
.messagename span{
    font-size: 15px;
    width:100%;
    overflow:hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
}
.messagetime{
    height:100%;
    display: grid;
   place-items: center;
   padding:10px;
   font-size: 12px;
   color: #56789a;
}  

/* 右侧内容区样式 */
.messagecontent{
    height:100%;
    width:60%;
}
.messagedetaillayout{
    padding:20px;
    padding-left:5px;
    background-color: #2c3e50;
    height:100%;
    width:100%;
    border-radius: 0px 20px 20px 0px;
}
.messagedetail{
    background-image: url("/img/2051855.jpg");
    background-size: cover;
    height:100%;
    width:100%;
    border-radius: 5px 10px 10px 5px;
    color:rgb(247, 249, 252);
}

.messageshow{
    width:100%;
    height:80%;
    padding:5px;
    border-radius: 5px 10px 0px 0px;
    background-color: #022e38;
    opacity:0.95;
    /* 设置滚动条停留在底部 */
    overflow:auto;   
    display: flex;
    flex-direction: column-reverse;
}
/* .messageshow ul{
    height: 100%; 
    overflow:auto;  
}  */

.messageshow li{
    margin-top:15px;
}
/* 好友聊天信息样式 */
.messagedetailli1{
    display: flex;
    justify-content: flex-start;
}
.messagedetailli1 #message{
    background-color: white;
    color:black;
    padding: 8px;
    border-radius: 10px;
    margin-left:10px;
    max-width: 400px;
    font-size: 14px;  
}

#avatar{
    height: 40px;
    width:  40px;
}

/* 自己聊天信息样式 */
.messagedetailli2{
    display: flex;
    justify-content: flex-end;
}
.messagedetailli2 #message{
    background-color: rgb(146, 241, 164);
    color:black;
    padding: 8px;
    border-radius: 10px;
    margin-right:10px;
    max-width: 400px;
    font-size: 14px;  
}

.messagedetailli1 #name{
    font-size: 8px;
    color: rgb(239, 245, 245);
    padding-bottom: 5px;
    margin-left:10px;
}
.messagedetailli2 #name{
    font-size: 8px;
    color: rgb(239, 245, 245);
    padding-bottom: 5px;
    margin-right:10px;
    display: flex;
    justify-content: flex-end;
}

/* 图片和文件类型消息样式 */
#message img{
    width:100%;
}

.fileshow{
    display: flex;
    justify-content: flex-start;
}
.fileshowname{
    padding: 10px;
    margin-left: 3px;
    border-radius: 5px;
    background-color:#f4cd78;
}
.fileshowname p{
padding-bottom: 10px;
}

.flexend{
    display: flex;
    justify-content: flex-end;
}
.fileshowname a{
    text-decoration: none;
    color: #067af6;
}


/* 信息输入框样式 */
.messageinput{
    width:100%;
    height:20%;
    padding:5px;
    background-color: white;
    border-radius: 0px 0px 10px 5px;
}

.messageinputform{
    width:100%;
    /* height:75% */
    margin-bottom: 10px;
}
.messageinputbutton{
    width: 100%;
    /* height:25%; */
    display: flex;
    justify-content: flex-end;
}
.avatarandname{
   display: flex;
   justify-content: flex-start;
   margin-top: 10px;
   margin-bottom: 40px;
}
.avatarandname span{
    display: block;
    padding-right:20px
}
.filemessage{
    margin-top: 30px;
    /* border-top:2px solid rgb(229, 229, 229); */
    /* padding-top:20px;
    padding-bottom:20px; */
}
.filemessage span{
    background-color: rgb(47, 162, 249);
    color: white;
    padding-left:15px;
    padding-right:15px;
    padding-top:8px;
    padding-bottom:8px;
    border-radius: 2px;
    margin-right: 15px;
    font-size: 10px;
}
</style>